package door.smartlift.top.controller;

import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import door.smartlift.top.common.utils.StringUtil;
import door.smartlift.top.common.utils.WxSession;
import door.smartlift.top.domain.IotGoods;
import door.smartlift.top.domain.WxUser;
import door.smartlift.top.exception.MyDefineException;
import door.smartlift.top.resultBean.ResultBean;
import door.smartlift.top.service.IotGoodsService;
import door.smartlift.top.service.IotOrderService;
import door.smartlift.top.service.WxLoginService;
import door.smartlift.top.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Admin
 * @date 2018/4/1
 */
@Slf4j
@RestController
@RequestMapping("wx")
public class WxController {

    @Autowired
    private IotGoodsService iotGoodsService;

    @Autowired
    private WxLoginService wxLoginService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private IotOrderService iotOrderService;

    @RequestMapping(value = "/goods", method = RequestMethod.GET, headers = "Accept=application/json")
    public ResultBean<Map> goods(@RequestParam String deviceNum){

        checkSession();
        Map data=this.iotGoodsService.selectByDeviceNum(deviceNum);
        return new ResultBean<>(data);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResultBean<Integer> saveUser(@RequestBody WxUser wxUser){

        checkSession();
        int count=this.wxUserService.saveWxUser(wxUser);
        return new ResultBean<>(count);
    }

    @RequestMapping(value = "/unifiedOrder", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResultBean unifiedOrder(@RequestBody IotGoods iotGoods) throws Exception{

        checkSession();
        Map data=this.iotOrderService.doUnifiedOrder(iotGoods);
        return new ResultBean<>(data);
    }

    @RequestMapping(value = "/notify")
    public String doNotify(HttpServletRequest request) throws Exception{

        return iotOrderService.conformWxPay(request);

    }

    private void checkSession(){

        String sessionId= WxSession.getSessionId();

        if (! StringUtil.isNotEmpty(sessionId)){

            throw new MyDefineException("请先登录");
        }

        /*WxUser wxUser=this.wxLoginService.findWxUserBySessionId(sessionId);

        long time=System.currentTimeMillis();

        if (wxUser == null || time>wxUser.getExpireDate()){

            throw new MyDefineException("登陆超时，请重新登陆");
        }*/

    }
}
